package com.honglang.aop.impl;

import java.io.FileNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.stream.XMLStreamException;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.WebApplicationContext;

import com.honglang.module.article.service.BlogArticleService;
import com.honglang.rss.impl.RSSStreamWriter;
import com.honglang.rss.impl.RSSUtil;
import com.honglang.struts2.action.BaseAction;


@Aspect
public class RSSAspect {
	private static final Logger logger = Logger.getLogger(RSSAspect.class);
	
	@Pointcut("execution(* com.honglang..action.*.*(..))")
	protected void rssUpdatePointCut(){};
	
	@After("rssUpdatePointCut() && " +"@annotation(com.honglang.aop.impl.UpdateRSSPointCut)")
	public void updateFeed(JoinPoint jp){
		logger.info("Make rss file");
		BaseAction baseAction = (BaseAction)jp.getTarget();
		HttpServletRequest request =  baseAction.getRequest();
		WebApplicationContext  webApplicationContext = baseAction.getWebApplicationContext();
		BlogArticleService blogArticleService = (BlogArticleService)webApplicationContext.getBean("blogArticleService");
		String rssXml = request.getSession().getServletContext().getRealPath("/")  + "/feed/rssFeed.xml";
		String urlPrefix = request.getContextPath();
		try {
			//RSSEventWriter rssWriter = new RSSEventWriter(rssXml);
			//rssWriter.createRss(RSSUtil.createChannel(blogArticleService.getRecentBlogArticle(5), urlPrefix));
			RSSStreamWriter rssStreamWriter = new RSSStreamWriter(rssXml,"UTF-8");
			rssStreamWriter.createRss(RSSUtil.createChannel(blogArticleService.getRecentBlogArticle(50), urlPrefix));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			logger.error("File not Found");
			e.printStackTrace();
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			logger.error("Something wrong with process rss xml file");
			e.printStackTrace();
		} 
		logger.info("Rss file Done!");
	}
	
	
}
